<script setup>
import { cloneDeep } from 'lodash';
import infoDialog from './components/infoDialog.vue'
import {
  getAllFormKeyAsync,
  getAllUserAsync,
  getAllGroupAsync,
  addFlowAsync
} from '@/api/flowManagement.js'

import { ref, onMounted, onBeforeUnmount } from 'vue'
import router from '@/router';
const myFrame = ref(null)

// 获取myframe的内容
const getMyFrameMessage = (event) => {
  const xml = event.data.xml
  const name = event.data.process.name
  addFlow(xml, name)
}

// 获取到流程详情
window.addEventListener("message", getMyFrameMessage);

const loading = ref(true)
const dialogVisible = ref(false)

const optionList = ref([])

//获取表单标识
const getAllFormKey = async () => {
  try {
    const res = await getAllFormKeyAsync()
    if (res.data && Array.isArray(res.data) && res.data.length) {
      optionList.value = res.data.map(item => ({ label: item.description, value: item.modelKey }))
      optionList.value = [{ label: '表单描述↓↓', value: '↓↓表单标识', disabled: true }].concat(optionList.value)
      dialogVisible.value = true
    }
    console.log('%c [  ]-41', 'font-size:13px; background:pink; color:#bf2c9f;', res)
  } catch (error) {
    console.log('%c [ error ]-40', 'font-size:13px; background:pink; color:#bf2c9f;', error)

  }
}

const userList = ref([])
//获取候选人
const getAllUser = async () => {
  try {
    const res = await getAllUserAsync()
    if (res.data && Array.isArray(res.data) && res.data.length) {
      userList.value = res.data.map(item => ({ name: item.fullName, id: item.id }))

    }
  } catch (error) {
    console.log('%c [ error ]-44', 'font-size:13px; background:pink; color:#bf2c9f;', error)

  }
}

//获取候选组
const groupList = ref([])
const getAllGroup = async () => {
  try {
    const res = await getAllGroupAsync()
    if (res.data && Array.isArray(res.data) && res.data.length) {
      groupList.value = res.data.map(item => ({ name: item.name, id: item.id }))

    }
  } catch (error) {
    console.log('%c [ error ]-44', 'font-size:13px; background:pink; color:#bf2c9f;', error)

  }
}
//配置内容数据
const hasData = computed(() => {
  return groupList.value.length && userList.value.length
})

//部署
const addFlow = async (xml, name) => {
  try {
    const fileContent = xml
    // 创建 Blob 对象
    const blob = new Blob([fileContent], { type: 'text/xml' })
    // 创建 FormData 对象并添加文件
    const formData = new FormData()
    formData.append('file', blob, `${name}.xml`)
    formData.append('name', name)
    const res = await addFlowAsync(formData)
    if (res && res.code + '' === '200') {

      ElMessageBox.confirm(
        '是否请前往【流程定义】查看流程！?',
        '部署成功',
        {
          confirmButtonText: '前往查看',
          cancelButtonText: '继续修改',
          type: 'success',
        }
      ).then(() => {
        router.push({ name: 'flowList' })
      }).catch((error) => {
        console.log('%c [ error ]-103', 'font-size:13px; background:pink; color:#bf2c9f;', error)
      })
    } else if (res && res.code + '' !== '200') {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    console.log('%c [ error ]-79', 'font-size:13px; background:pink; color:#bf2c9f;', error)
  }

}

onBeforeMount(() => {

})

onMounted(async () => {
  const res = await Promise.all([
    getAllUser(),
    getAllGroup()
  ])

  console.log('%c [  ]-125', 'font-size:13px; background:pink; color:#bf2c9f;', res)
  if (res) {

    myFrame.value.onload = () => {
      let postMsg = {
        xml: "",
        // 后端查询到的xml，新建则为空串
        users: cloneDeep(userList.value),
        groups: cloneDeep(groupList.value),
        categorys: [
          { name: "OA1", id: "oa" },
          { name: "财务1", id: "finance" },
        ],
        isView: false
      }
      // 设置初始化值
      myFrame.value.contentWindow.postMessage(postMsg, "*")
    }
  }

})

onBeforeUnmount(() => {
  window.removeEventListener('message', getMyFrameMessage)
})

watchEffect(() => {
  if (hasData.value) {
    loading.value = false
  }
})


</script>

<template>
  <div class='flowChart-container' v-loading="loading">
    <el-button class="btn" type='info' @click="getAllFormKey">
      点击查看表单标识key,复制到<span class="tips">【开始】</span>的<span class="tips">【表单标识key】</span>中
    </el-button>
    <iframe src="/static/workFlow/index.html" ref="myFrame" frameborder="0" width="100%">
    </iframe>
  </div>
  <infoDialog :visible="dialogVisible" :optionList="optionList" @closeDialog="dialogVisible = false" />
</template>

<style lang="scss" scoped>
.flowChart-container {
  background-color: #fff;
  height: 100%;

  .btn {
    width: 100%;
  }

  .tips {
    color: rgb(251, 187, 187);
    font-weight: 700;
  }

  iframe {
    height: 80vh;
  }
}
</style>